package com.baixun.gassystem.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baixun.gascommon.config.ApiConfig;
import com.baixun.gascommon.utils.HttpClientUtil;
import com.baixun.gascommon.utils.RedisUtils;
import com.baixun.gasentity.entity.Point;
import com.baixun.gasentity.vo.VideoPlaybackVO;
import com.baixun.gassystem.mapper.PointMapper;
import com.baixun.gassystem.mapper.VideoPlaybackMapper;
import com.baixun.gassystem.service.HomePageService;
import com.baixun.gassystem.service.VideoPlaybackService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class VideoPlaybackServiceImpl implements VideoPlaybackService {

    @Autowired
    private VideoPlaybackMapper videoPlaybackMapper;


    @Autowired
    private HomePageService homePageService;

    @Autowired
    private PointMapper pointMapper;

    @Autowired
    private  RedisUtils redisUtils;


    /**视频监控（实时监控）
     * @param page
     * @param size
//     * @param pointId 监控点位ID
//     * @param protocol 播放协议类型
     * @return
     * @throws Exception
     */
    @Override
    public IPage<VideoPlaybackVO> getVideoPlaybackByPointAndProtocol(Integer page, Integer size) throws Exception {

        if (size == null) {
            size = 10;
        }
        if (page == null) {
            page = 1;
        }

        // 创建分页对象
        Page<VideoPlaybackVO> pagination = new Page<>(page, size);

        // 调用API获取指定点位和协议的签名URL数据
        Map<String, Map<String, List<String>>> videoRecordUrl = homePageService.getVideo();

        // 查询所有 pointId
        QueryWrapper<Point> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("pointId");
        List<Object> pointIds = pointMapper.selectObjs(queryWrapper);

        // 检查 pointIds 和 videoRecordUrl 是否为 null
        if (pointIds == null || pointIds.isEmpty()) {
            throw new Exception("从数据库获取的 pointIds 列表为空！");
        }
        if (videoRecordUrl == null || videoRecordUrl.isEmpty()) {
            throw new Exception("视频回放记录 videoRecordUrl 为空！");
        }

        // 用于保存所有符合条件的记录
        List<VideoPlaybackVO> videoPlaybackList = new ArrayList<>();

        // 遍历 videoRecordUrl 的 key
        for (Map.Entry<String, Map<String, List<String>>> entry : videoRecordUrl.entrySet()) {
            String key = entry.getKey();
            Map<String, List<String>> nestedMap = entry.getValue();

            // 检查 pointIds 是否包含当前 key
            if (pointIds.contains(key)) {
                System.out.println("Key " + key + " 不在 pointIds 中，跳过处理。");
                continue;
            }

            // 如果 key 存在于 pointIds 中，继续处理 nestedMap
            if (nestedMap == null) {
                System.out.println("Key " + key + " 对应的值为 null，跳过处理。");
                continue;
            }

            // 获取 urls, mainUrls, subUrls
            List<String> urls = nestedMap.get("urls");
            List<String> mainUrls = nestedMap.get("mainUrls");
            List<String> subUrls = nestedMap.get("subUrls");

            // 检查是否为 null
            if (urls == null || mainUrls == null || subUrls == null) {
                System.out.println("Key " + key + " 的某些字段为 null，跳过处理。");
                continue;
            }

            // 创建 VideoPlaybackVO 对象并设置 URL 列表
            VideoPlaybackVO videoPlaybackVO = new VideoPlaybackVO();
            videoPlaybackVO.setUrls(urls.toString());
            videoPlaybackVO.setMainUrls(mainUrls.toString());
            videoPlaybackVO.setSubUrls(subUrls.toString());

            // 添加到结果列表
            videoPlaybackList.add(videoPlaybackVO);
        }

        // 如果没有符合条件的记录，返回空分页
        if (videoPlaybackList.isEmpty()) {
            return pagination;
        }

        // 根据分页参数截取结果
        int start = (page - 1) * size;
        int end = Math.min(start + size, videoPlaybackList.size());
        List<VideoPlaybackVO> paginatedList = videoPlaybackList.subList(start, end);

        // 设置分页数据
        pagination.setRecords(paginatedList);
        pagination.setTotal(videoPlaybackList.size());

        // 返回分页结果
        return pagination;
    }

    /**
     * 实时监控【根据用户权限来获取】
     * 播放协议写死了可以根据后期业务修改
     */
    @Override
    public IPage<VideoPlaybackVO> getVideoByUserId(Integer page, Integer size,Long userId, Long pointId) throws Exception {
        // 从 Redis 中获取 token
        String tokenkey = "token:"+userId;
        String token = redisUtils.get(tokenkey);
        if (token == null || token.isEmpty()) {
            throw new Exception("No valid token found in Redis.");
        }


        String videourl = ApiConfig.DOMAIN + ApiConfig.POINTS_API+pointId+"/signed_url?protocol=rtmp";
        // 请求头信息，包含动态获取的 token
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie", "SAAS_SESSION=" + token);
        headers.put("Content-Type", "application/json; charset=UTF-8");
        JSONObject jsonResponse = JSON.parseObject(HttpClientUtil.sendGetRequest(videourl, headers));
        // 获取播放链接数组
        List<String> urls = jsonResponse.getJSONArray("urls").toJavaList(String.class);
        List<String> mainUrls = jsonResponse.getJSONArray("mainUrls").toJavaList(String.class);
        List<String> subUrls = jsonResponse.getJSONArray("subUrls").toJavaList(String.class);

        // 将数据存入结果映射
        Map<String, List<String>> links = new HashMap<>();
        links.put("urls", urls);
        links.put("mainUrls", mainUrls);
        links.put("subUrls", subUrls);


        return (IPage<VideoPlaybackVO>) links;
    }


    /**
     * 判断是历史还是云端
     * 如果返回结果为null，返回false，则不是云端
     */
    public  boolean isCloud(Long pointId) {
       String cloud=pointMapper.selectCloud(pointId);
       if (cloud!=null) {
           return true;
       }
        return false;
    }



    /**
     * 视频监控（历史监控）
     */
    @Override
    public String selectVideoHistoryPlaybackRecords(Integer page, Integer size, String startTime, String endTime, Long pointId, Long userId) throws Exception {
        if (size==null){
            size=10;
        }
        if (page==null){
            page=1;
        }
        // 创建分页对象
        Page<VideoPlaybackVO> pagination = new Page<>(page, size);

        String tokenKey = "token:" + userId;
        String token = redisUtils.get(tokenKey);
        if (token == null || token.isEmpty()) {
            throw new Exception("No valid token found in Redis.");
        }

        if (!isCloud(pointId)){
            String local = ApiConfig.DOMAIN + ApiConfig.RECORDING + pointId + "/localRecording"
                    + "&beginTime=" + startTime
                    + "&endTime=" + endTime;
            // 请求头信息，包含动态获取的 token
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Cookie", "SAAS_SESSION=" + token);
            headers.put("Content-Type", "application/json; charset=UTF-8");
            return  HttpClientUtil.sendGetRequest(local, headers);
        }else {
            String cloud = ApiConfig.DOMAIN + ApiConfig.RECORDING + pointId + "/recording"
                    + "?pageNum=" + page
                    + "&pageSize=" + size
                    + "&beginTime=" + startTime
                    + "&endTime=" + endTime;
            // 请求头信息，包含动态获取的 token
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Cookie", "SAAS_SESSION=" + token);
            headers.put("Content-Type", "application/json; charset=UTF-8");
           return HttpClientUtil.sendGetRequest(cloud, headers);
        }
    }



}
